package com.cyan.app.workflow.activity.TQM;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.BmsBarcodeBean;
import com.cyan.app.workflow.bean.BmsfshBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.activity.Common.WorkProcedureActivity;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshBase;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshListView;
import com.google.gson.Gson;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by DXW on 2016-04-14.
 */
public class BmsIPQCActivity extends BaseActivity {
    private TextView mTextView;
    private Button mButton;
    private EditText mEditTextManno;
    private EditText mEditTextBarcode;
    public static final String TAG = "TqmMannoActivity";
    private Context context = null;
    private ShowTipDialog showdialog = new ShowTipDialog();
    private PopupWindow mPopWindow;
    private View titleView;
    public static final int REFRESH_VIEW = 1;               //加载界面
    public static final int REFRESH_SEACH = 2;              //查询
    public static final int REFRESH_QC = 3;                 //质检
    private PullToRefreshListView mPullToRefreshExpandableListView;
    private PullToRefreshListView mPullToRefreshNoDataListView;
    private ListView mPoolShowListView;
    private TqmMannoAdapter mPoolShowListViewAdapter;
    private List<BmsfshBean.Bmsfsh> resultList;
    private EditText mEditTextPross;
    private static final String PROSSCODE = "tqm_manno_pross";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ipqc_bmsbarcode);
        titleBar();
        initView();
        mHandler.sendEmptyMessage(REFRESH_VIEW);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0001 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                mEditTextManno.setText(String.valueOf(result));
            }
        }
        if(requestCode == 0x0002 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("OID");
                for (int i = resultList.size() - 1; i >= 0; i--) {
                    if (resultList.get(i).getOID().equals(result))
                        resultList.remove(i);
                }
                refreshPoolListView(resultList);
            }
        }
        if(requestCode == 0x0003 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("prosscode");
                mEditTextPross.setText(String.valueOf(result));
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(PROSSCODE,result).commit();
            }
        }
        if(requestCode == 0x0004 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                mEditTextBarcode.setText(String.valueOf(result));
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    private void initView(){
        mPullToRefreshNoDataListView = (PullToRefreshListView) findViewById(R.id.ipqc_manno_show_no);
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshNoDataListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessage(REFRESH_VIEW);
            }
        });
        ListView listView = mPullToRefreshNoDataListView.getRefreshableView();
        listView.setAdapter(mNoDataAdapter);

        mPullToRefreshExpandableListView = (PullToRefreshListView) findViewById(R.id.ipqc_manno_show_list);
        mPoolShowListView = mPullToRefreshExpandableListView.getRefreshableView();
        mPullToRefreshExpandableListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessage(REFRESH_VIEW);
            }
        });
        mPoolShowListViewAdapter = new TqmMannoAdapter(this, new ArrayList<BmsfshBean.Bmsfsh>());
        mPoolShowListView.setAdapter(mPoolShowListViewAdapter);

        mPullToRefreshNoDataListView.setPullToRefreshEnabled(true);
        mPullToRefreshExpandableListView.setPullToRefreshEnabled(true);

    }
    private void titleBar() {
        mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("完工质检");
        titleView = (View) findViewById(R.id.layout_main_ui_top2_title);
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);
        mButton.setText("筛选");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFilterDialog();
            }
        });
    }
    private void showFilterDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.tqm_filter, null);
        mPopWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        //mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindow.showAsDropDown(titleView);
        mEditTextManno =  (EditText) view.findViewById(R.id.tqm_man_seach_manno);
        //mEditTextManno.setInputType(InputType.TYPE_NULL);
        Button mButtonManno=(Button)view.findViewById(R.id.tqm_man_seach_manno_sm);
        mButtonManno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(BmsIPQCActivity.this, CaptureActivity.class), 0x0001);
            }
        });

        mEditTextBarcode =  (EditText) view.findViewById(R.id.tqm_man_seach_barcode);
        Button mButtonBarcode=(Button)view.findViewById(R.id.tqm_man_seach_barcode_sm);
        mButtonBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(BmsIPQCActivity.this, CaptureActivity.class), 0x0004);
            }
        });

        mEditTextPross = (EditText) view.findViewById(R.id.tqm_man_seach_prosscode);
        final String pross = PreferenceManager.getDefaultSharedPreferences(this).getString(PROSSCODE,null);
        if(pross!=null){
            mEditTextPross.setText(String.valueOf(pross));
        }
       // mEditTextPross.setInputType(InputType.TYPE_NULL);

        Button  mButtonPross = (Button) view.findViewById(R.id.tqm_man_seach_prosscode_sm);
        mButtonPross.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(BmsIPQCActivity.this, WorkProcedureActivity.class);
                startActivityForResult(intent,0x0003);
            }
        });
        Button mSubmit = (Button) view.findViewById(R.id.tqm_man_seach_submit);
        //查询事件
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                if(mEditTextPross.getText().toString().isEmpty()&&pross!=null){
                    PreferenceManager.getDefaultSharedPreferences(BmsIPQCActivity.this).edit().remove(PROSSCODE).commit();
                }
                IPQCBarcodeAsyncLoader task = new IPQCBarcodeAsyncLoader();
                    task.execute(  mEditTextPross.getText().toString(),mEditTextManno.getText().toString()
                    ,mEditTextBarcode.getText().toString());
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_VIEW:
                    FetchData();
                    break;
                case REFRESH_SEACH:
                    //mShowLoadingDialog = false;
                    //fetchData(mFilterSubType, "0");
                    break;
                case REFRESH_QC:
                    if(!AppData.getInstance().isUserLogin()){
                        //AppUtils.showTip(DDActivity.this, "请先登录后再操作。");
                        return;
                    }
                    //new DDActivity.grabLoader().execute(msg.obj.toString(), String.valueOf(REFRESH_GRAB));
                    break;
                default:
                    break;
            }
        }
    };
    private void FetchData(){
        final String pross = PreferenceManager.getDefaultSharedPreferences(this).getString(PROSSCODE,null);
        if(pross!=null){
            new IPQCBarcodeAsyncLoader().execute(pross,"","");
        }else {
            new IPQCBarcodeAsyncLoader().execute();
        }
    }
    private void FetchDataEnd() {
        onRefreshComplete();
        refreshPoolListView(resultList);
    }
    //刷新列表
    private void refreshPoolListView(List<BmsfshBean.Bmsfsh> list) {
        if (list == null) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }

        if (list.size() == 0) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshExpandableListView.setVisibility(View.VISIBLE);

        TqmMannoAdapter adapter = new TqmMannoAdapter(this,null);
        mPoolShowListView.setAdapter(adapter);
        adapter.setDatas(list);
        adapter.notifyDataSetChanged();
    }
    private void onRefreshComplete() {
        if (mPullToRefreshExpandableListView.isRefreshing()) {
            mPullToRefreshExpandableListView.onRefreshComplete();
        }

        if (mPullToRefreshNoDataListView.isRefreshing()) {
            mPullToRefreshNoDataListView.onRefreshComplete();
        }
    }
    //没数据处理
    BaseAdapter mNoDataAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView != null) {
                return convertView;
            }
            convertView = LayoutInflater.from(BmsIPQCActivity.this).inflate(R.layout.layout_main_nodata, null);
            return convertView;
        }
    };
    public class IPQCBarcodeAsyncLoader extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            showdialog.showDialog(BmsIPQCActivity.this);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            String action ="GetBmsIPQC";
            try{
                JSONObject param = new JSONObject();
                param.put("TQMKind", "IPQC");
                param.put("FactoryID", HttpConfig.Main_FactoryID);
                param.put("UserNo", AppData.getInstance().getUserId());
                param.put("Connectstring", AppData.getInstance().getConnectstring());
                if(params.length>0) {
                    param.put("ProcedureNo", params[0]);
                    param.put("OrderNumber", params[1]);
                    param.put("Barcode", params[2]);
                }
                result= GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, action, param.toString(), getApplicationContext());
            }catch (Exception e){
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null||s.isEmpty()) {
                showdialog.closeDialog();
                return;
            }
            BmsfshBean commonBean = new Gson().fromJson(s, BmsfshBean.class);
            if (commonBean!=null) {
                resultList = commonBean.getResult();
            }
            FetchDataEnd();
            showdialog.closeDialog();
        }
    }

    public class TqmMannoAdapter extends BaseAdapter {
        List<BmsfshBean.Bmsfsh> mpoolList;
        private LayoutInflater inflater = null;
        public TqmMannoAdapter(Context context,List<BmsfshBean.Bmsfsh> list) {
            inflater = LayoutInflater.from(context);
            if (list != null) {
                mpoolList = list;
            }
        }
        public void setDatas(List<BmsfshBean.Bmsfsh> poolList) {
            if (poolList != null) {
                mpoolList = poolList;
            }
        }
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return   mpoolList == null ? 0 : mpoolList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder ;
            if (convertView == null) {
                holder = new ViewHolder();
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER_VERTICAL;
                convertView = inflater.inflate(R.layout.tqm_manno_list, null);
                holder.tqm_list_prossname = (TextView) convertView.findViewById(R.id.tqm_manno_list_prossname);
                holder.tqm_list_type = (TextView) convertView.findViewById(R.id.tqm_manno_list_type);
                holder.tqm_list_itnbr = (TextView) convertView.findViewById(R.id.tqm_manno_list_itnbr);
                holder.tqm_list_itdsc = (TextView) convertView.findViewById(R.id.tqm_manno_list_itdsc);
                holder.tqm_list_manno = (TextView) convertView.findViewById(R.id.tqm_manno_list_manno);
                holder.tqm_list_accqty = (TextView) convertView.findViewById(R.id.tqm_manno_list_accqty);
                holder.tqm_list_username = (TextView) convertView.findViewById(R.id.tqm_manno_list_username);
                holder.tqm_list_date = (TextView) convertView.findViewById(R.id.tqm_manno_list_date);
                holder.tqm_right_layout = convertView.findViewById(R.id.tqm_manno_list_right_layout);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            final BmsfshBean.Bmsfsh obj = mpoolList.get(position);
            holder.tqm_list_prossname.setText(obj.getProcedureName());
            holder.tqm_list_itnbr.setText(obj.getItemNumber());
            holder.tqm_list_itdsc.setText(obj.getItemName());
            holder.tqm_list_manno.setText(obj.getOrderNumber());
            holder.tqm_list_accqty.setText(obj.getGodQty().toString().replace(".0",""));
//            if (obj.getQctype()==1) {
//                holder.tqm_list_type.setText("首检");
//                holder.tqm_list_accqty.setTextColor(Color.parseColor("#fe5052"));
//            } else {
//                holder.tqm_list_type.setText("再检");
//                holder.tqm_list_accqty.setTextColor(Color.parseColor("#60ca82"));
//            }
            holder.tqm_list_type.setText("完工检验");
            holder.tqm_list_username.setText(obj.getWorkManName());
            holder.tqm_list_date.setText(obj.getTranDate());
            holder.tqm_right_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("ipqcBarcodeDetail", (BmsfshBean.Bmsfsh)obj);
                    Intent intent = new Intent();
                    intent.setClass(BmsIPQCActivity.this, BmsIPQCDetailActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 0x0002);
                }
            });

            return convertView;
        }

        class ViewHolder {
            TextView tqm_list_prossname;
            TextView tqm_list_type;
            TextView tqm_list_itnbr;
            TextView tqm_list_itdsc;
            TextView tqm_list_manno;
            TextView tqm_list_accqty;
            TextView tqm_list_username;
            TextView tqm_list_date;
            View tqm_right_layout;
        }
    }
}


